import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

//通过这个类来表示解析后的结果
class JsonData{
    public int userId;
    public int classId;
}

@WebServlet("/postParameterJson")
public class PostParameterJson extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //先把整个body读出来
        String body = readBody(req);
        //使用jackson来解析
        //先创建一个jackson的核心对象ObjectMapper
        ObjectMapper objectMapper = new ObjectMapper();
        JsonData jsonData = objectMapper.readValue(body,JsonData.class);
        //以上就完成了Json格式的字符串到Java对象的解析过程
        resp.getWriter().write(String.format("userId: %s; classId: %s <br>",jsonData.userId,jsonData.classId));
    }
    private String readBody(HttpServletRequest req) throws IOException{
        //读取body需要根据req.getInputStream得到一个流对象，从这个流对象中读取
        InputStream inputStream = req.getInputStream();
        //通过contentLength拿到请求中的body字节数
        int contentLength = req.getContentLength();
        byte[] buffer = new byte[contentLength];
        inputStream.read(buffer);
        return new String(buffer,"utf-8");
    }
}
